import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import del from 'rollup-plugin-delete';
import pkg from './package.json' with { type: 'json' };
import path from 'path';
import { readdirSync } from 'fs';

// 创建自定义插件
function controllersPlugin() {
  return {
    name: 'controllers-plugin',
    buildStart() {
      // 读取 controllers 目录下的所有控制器文件
      const controllersDir = path.join(process.cwd(), 'src/controllers');
      const files = readdirSync(controllersDir);

      // 将所有控制器文件添加到 Rollup 的构建队列中
      for (const file of files) {
        if (file.endsWith('controller.ts')) {
          this.emitFile({
            type: 'chunk',
            id: path.join(controllersDir, file),
          });
        }
      }
    },
  };
}

export default {
  input: 'src/main.ts',
  output: {
    dir: 'dist',
    format: 'es',
    sourcemap: true,
    // 启用代码分割
    manualChunks(id) {
      // 将 controllers 目录下的文件单独打包
      if (id.includes('controllers')) {
        const fileName = path.basename(id.split('/').pop()).replace('.ts', '');
        return `controllers/${fileName}`;
      }
    },
  },
  plugins: [
    del({ targets: 'dist/*' }),
    controllersPlugin(),
    typescript({
      // 确保装饰器元数据被保留
      compilerOptions: {
        emitDecoratorMetadata: true,
        experimentalDecorators: true,
      },
    }),
    resolve(),
    commonjs(),
  ],
  // 排除不需要打包的外部依赖
  // external: [ ...Object.keys(pkg.dependencies)]
  external: Object.keys(pkg.dependencies),
};
